package com.books.controller.order;

import com.books.model.bo.Result;
import com.books.model.dto.BuyOrderDto;
import com.books.model.entity.order.BuyOrder;
import com.books.model.entity.order.OrderList;
import com.books.model.entity.shopping.ShoppingCar;
import com.books.service.address.IAddressService;
import com.books.service.shoppingcar.IShoppingCarService;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author ZhouRui
 * @title: 码上就来
 * @projectName cbstore-spring-boot
 * @description: TODO
 * @date 2021/10/1114:21
 */
@RestController
@RequestMapping(value = "/buy",method = RequestMethod.GET)
public class BuyOrderController {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IShoppingCarService shoppingCarService;

    @Autowired
    private BuyOrder buyOrder;

    @Autowired
    private IAddressService addressService;

    @Autowired
    private CuratorFramework curatorFramework;

    @PostMapping
    @ResponseBody
    public Result saveorder(Integer uid,Integer pid,Integer did,Double tmoney,String date){
        List<String> bid=new ArrayList<>();
        String uuid=date.replace(":","").replace(" ","").replace("-","")+uid;
        //获取锁
        InterProcessSemaphoreMutex balanceLock = new InterProcessSemaphoreMutex(curatorFramework, "/zktest" + uuid);
        // 执行加锁操作
        try {
            balanceLock.acquire();
            System.out.println("已经加锁了, name=" + uuid);
            String buyid;
            buyOrder.setBuyId(uuid);
            buyOrder.setAddressId(did);
            buyOrder.setBuyTime(date);
            buyOrder.setPayId(pid);
            buyOrder.setTotalMoney(tmoney);
            buyOrder.setUserId(uid);
            buyOrder.setStateId(1);
            redisTemplate.opsForValue().set("ocode"+buyOrder.getBuyId(),buyOrder,30, TimeUnit.MINUTES);
            if(redisTemplate.opsForValue().get("ucode"+uid)==null){
                bid.add(buyOrder.getBuyId());
                redisTemplate.opsForValue().set("ucode"+uid,bid,30,TimeUnit.MINUTES);
            }
            else {
                buyid=buyOrder.getBuyId();
                bid= (List<String>) redisTemplate.opsForValue().get("ucode"+uid);
                bid.add(buyid);
                redisTemplate.opsForValue().set("ucode"+uid,bid,30,TimeUnit.MINUTES);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // 释放锁资源
            try {
                balanceLock.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new Result("200","已成功下单",uuid);
    }

    @PostMapping("/add")
    @ResponseBody
    public Result addorder(HttpServletRequest request) {
        HttpSession session = request.getSession();
        List<ShoppingCar> shoppingCars;
        List<OrderList> orderLists = new ArrayList<>();
        shoppingCars = (List<ShoppingCar>) session.getAttribute("carlist");
        // 获取锁
        InterProcessSemaphoreMutex balanceLock = new InterProcessSemaphoreMutex(curatorFramework, "/zktest"+buyOrder.getBuyId());
        // 执行加锁操作
        try {
            balanceLock.acquire();
            System.out.println("已经加锁了, name=" + buyOrder.getBuyId());
            buyOrder = (BuyOrder) redisTemplate.opsForValue().get("ocode" + buyOrder.getBuyId());
            if (buyOrder == null) {
                return new Result("500", "订单已过期！");
            } else {
                for (int i = 0; i < shoppingCars.size(); i++) {
                    OrderList orderList = new OrderList();
                    orderList.setBuyId(buyOrder.getBuyId());
                    orderList.setBuyNum(shoppingCars.get(i).getNum());
                    orderList.setBuyPrice(shoppingCars.get(i).getTotal());
                    orderList.setProductId(shoppingCars.get(i).getBookId());
                    orderList.setBuyImg(shoppingCars.get(i).getImgUrl());
                    orderList.setBuyName(shoppingCars.get(i).getName());
                    orderList.setBuyDate(buyOrder.getBuyTime());
                    orderList.setBuyEvaluate(0);
                    orderList.setBuyStatus(1);
                    orderList.setBuyType(shoppingCars.get(i).getBookType());
                    orderList.setId(buyOrder.getBuyId() + shoppingCars.get(i).getBookId());
                    orderLists.add(orderList);
                    if (shoppingCarService.findById(shoppingCars.get(i).getId()) != null) {
                        shoppingCarService.delCarById(shoppingCars.get(i).getId());
                    }
                }
                redisTemplate.opsForValue().set("bcode" + buyOrder.getBuyId(), orderLists, 30, TimeUnit.MINUTES);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                balanceLock.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new Result("200", "订单生成成功！", buyOrder.getBuyId());
    }

    @GetMapping("/get")
    @ResponseBody
    public Result showordering(Integer uid){
        BuyOrder buyOrder;
        List<BuyOrderDto> buyOrderDtos=new ArrayList<>();
        List<String> bids;
        List<BuyOrder> buyOrders=new ArrayList<>();
        bids= (List<String>) redisTemplate.opsForValue().get("ucode"+uid);
        if(bids!=null){
            for (int i = 0; i < bids.size(); i++) {
                buyOrder= (BuyOrder) redisTemplate.opsForValue().get("ocode"+bids.get(i));
                if(buyOrder!=null){
                    buyOrders.add(buyOrder);
                }
            }
        }
        if(buyOrders!=null){
            for (int i = 0; i < buyOrders.size(); i++) {
                BuyOrderDto buyOrderDto = new BuyOrderDto();
                buyOrderDto.setBuyId(buyOrders.get(i).getBuyId());
                buyOrderDto.setBuyTime(buyOrders.get(i).getBuyTime());
                buyOrderDto.setPayId(buyOrders.get(i).getPayId());
                buyOrderDto.setStateId(0);
                buyOrderDto.setTotalMoney(buyOrders.get(i).getTotalMoney());
                buyOrderDto.setUserId(uid);
                buyOrderDto.setAddress(addressService.findById(buyOrders.get(i).getAddressId()).getAddress());
                buyOrderDtos.add(buyOrderDto);
            }
            return new Result("300","待支付订单",buyOrderDtos);
        }
        else if(buyOrders==null){
            redisTemplate.delete("ucode"+uid);
            return new Result("200","无待支付订单");
        }
        return new Result("200","无待支付订单");
    }
}
